<template>
  <Modal title="企业系统管理员" :transfer=false v-model="userForSelectModal"  :width=900 @on-cancel="modelClose">
    <Form ref="form1" :model="formItem" :label-width="120">
      <Row v-show="!switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="姓名：">
            <Input class="query-form-el" v-model="formItem.userName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="登录账号：">
            <Input class="query-form-el" v-model="formItem.loginId"></Input>
          </FormItem>
        </Col>
        <Col span="8">
<!--          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="姓名：">
            <Input class="query-form-el" v-model="formItem.userName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="登录账号：">
            <Input class="query-form-el" v-model="formItem.loginId"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="组织机构选择：">
            <cascader-dom ref="childOrg" class="query-form-el" :orgTree='true' @setOrgInfo='setOrgInfo'
                          :rootAffordIf="true" :department="true"></cascader-dom>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8" offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form" v-show="!model">
        <Col span="24">
          <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="modaltage()">新增
          </Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="buttonLoading" class="table" no-data-text="没有查询到相关数据!"
           highlight-row stripe border :columns="columns3" width="100%" :data="data1" size="small"
           @on-selection-change="selects">
    </Table>
    <Page :total="pagedata.total" :fromPage="pagedata.fromPage" :pageSize="pagedata.pageSize"
          @on-change="pageChange" @on-page-size-change='sizeChange' show-total show-sizer show-elevator/>
    <div slot="footer">
      <Button class='ivu-btn-save'  :loading="buttonLoading" @click="submit()">确定</Button>
      <Button class='ivu-btn-cancel' @click="modelClose">取消</Button>
    </div>
  </Modal>
</template>

<script>
import cascaderDom from "../../../components/cascader-dom.vue"
import {Api} from '../../../api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import zTree from "@/components/ztree.vue"
import Model from "@/views/safe/ptw/model/model";

export default {
  props: ['model','companyId','userForSelectModal','multiple'],
  components: {Model, cascaderDom,zTree},
  data() {
    return {
      reportSelectAll:[],
      orgModal:false,
      isHead: true,
      ztreeObj: null,
      positions:[],
      switchFlag: false,
      orgId: '',
      orgName: '',
      tableHeight: '',
      buttonLoading: false,
      selectedUserId:"",
      formItem: {
        userName: "",
        loginId: "",
        orgId: ""
      },
      formCustom: {
        userName: '',
        loginId: '',
        orgId: '',
        password: '',
        positionId: '1'
      },
      pagedata: {
        total: 0, //总条数
        fromPage: 1,//从n条开始
        pageSize: 10//每页多少条
      },
      tage: false,
      modal2: false,
      modifyRuleCustom:{
        userName: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        mobileNumber: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.formCustom.mobileNumber))) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        positionId: [{
          validator: (rule, value, callback) => {
            if (this.formCustom.positionId == null || this.formCustom.positionId == '' || this.formCustom.positionId == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        password: [{
          validator: (rule, value, callback) => {
            if (value == "")
              callback();
            var regex = new RegExp("(?=.*[0-9])(?=.*[a-zA-Z]).{9,16}");
            if (value.length < 9 || value.length > 16) {
              callback(new Error("请输入9~16位密码"));
            } else if (!regex.test(value)) {
              callback(new Error("密码必须同时包含字母、数字且至少9位"));
            } else {
              callback();
            }
          },
          required: true,
          trigger: 'blur'
        }],
        password1: [{
          validator: (rule, value, callback) => {
            if (this.formCustom.password != this.formCustom.password1) {
              callback('两次密码输入不一致')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
      },
      ruleCustom: {
        userName: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        loginId: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.formCustom.loginId))) {
              callback(new Error("请输入手机号"));
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        mobileNumber: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.formCustom.mobileNumber))) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        positionId: [{
          validator: (rule, value, callback) => {
            if (this.formCustom.positionId == null || this.formCustom.positionId == '' || this.formCustom.positionId == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        password: [{
          validator: (rule, value, callback) => {
            if (value == "")
              callback();
            var regex = new RegExp("(?=.*[0-9])(?=.*[a-zA-Z]).{9,16}");
            if (value.length < 9 || value.length > 16) {
              callback(new Error("请输入9~16位密码"));
            } else if (!regex.test(value)) {
              callback(new Error("密码必须同时包含字母、数字且至少9位"));
            } else {
              callback();
            }
          },
          required: true,
          trigger: 'blur'
        }],
        password1: [{
          validator: (rule, value, callback) => {
            if (this.formCustom.password != this.formCustom.password1) {
              callback('两次密码输入不一致')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
      },
      columns: [
        {type: 'selection', width: 60, fixed: 'left', align: 'center',},
        {title: "序号", width: 80, align: 'center', render: (h, params) => {
            return h('span', params.index + (this.pagedata.fromPage - 1) * this.pagedata.pageSize + 1);}},
        {title: '姓名', width: 100, align: 'center', key: 'userName'},
        {title: '登录账号', width: 100, align: 'center', key: 'loginId',},
        {title: '二级集团', minWidth: 200, align: 'center', key: 'twoLevelOrgName'},
        {title: '公司', minWidth: 200, align: 'center', key: 'companyName'},
        {title: '部门', minWidth: 200, align: 'center', key: 'orgName'},
        {title: '岗位', minWidth: 150, align: 'center', key: 'positionName'},
          {
              title: '操作',
              key: 'action',
              fixed: 'right',
              width: 80,
              align: 'center',
              render: (h, params) => {
                  return h('div', [
                      h('A', {
                          props: {
                              type: 'primary',
                              size: 'small'
                          },
                          style: {
                              fontSize: '14px'
                          },
                          on: {
                              click: () => {
                                  this.$emit('getSelectModelData', params.row);
                                  this.$emit('closeModel');
                              }
                          }
                      }, '选择')
                  ]);
              }
          }
      ],
      data1: [],
      orderTree: [
        {
          orgId:-1,
          title: '组织机构',
          expand: false,
          checked:false,
          loading:true,
          children:[],
        }
      ],
      setingTree: {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
          },
          key:{
            children: "childList"
          },
        },
        view: {
          showIcon: false,
          showLine:true
        }
      },
    }
  },
  watch: {
    "modal2": function (qw, er) {
      if (qw && this.tage) {
        setTimeout(() => {
          this.$refs.child.setCurrentOrg();
        }, 100)
      } else {
        this.$refs.child.resetCurrentOrg();
      }
    },
    userForSelectModal(newVal,val){
      if (newVal){
        this.query();
      }
    }

  },
    computed: {
        columns3() {
            const columns = [...this.columns];
            const columns1 = []
            columns.forEach(item => {
                if (this.multiple===true) {
                    if (item.type !== 'selection') {
                        columns1.push(item)
                    }
                } else {
                    if (item.key !== 'action') {
                        columns1.push(item)
                    }
                }
            })
            return columns1
        },
    },
  mounted: function () {
    if (this.model) {
      this.tableHeight = 400
    } else {
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    }
    this.query()
  },
  methods: {
    selects(data){
      this.reportSelectAll = [];
      data.forEach(item => {
        this.reportSelectAll.push({userId:item.userId})
      });
    },
    modelClose(){
      this.reportSelectAll = [];
      this.$emit('closeModel');
    },
    submit(){
      if (this.reportSelectAll.length > 0){
        this.buttonLoading=true
        this.$emit('getSelectModelData',this.reportSelectAll);
        this.buttonLoading=false
        this.$emit('closeModel');
      }else{
        this.$Message.warning('请选择用户');
      }

    },
    loadData (item, callback) {
      this.$http.get(Api.queryUserOrgsByUserId + "/" + this.selectedUserId + "/" + item.orgId).then(function(res){
        if(res.data.result == true){
          item.checked = false;
          item.selected = false;
          res.data.data.forEach(item1=>{
            item1.loading = false;
            item1.expand = false;
            item1.children = [];
            if(item1.checked == 'false'){
              console.log("111")
              item1.checked=false;
            }
            else{
              console.log("222")
              item1.checked=true;
            }
          })
          callback(res.data.data);
        }
      }, function(res){
        this.$Message.error('请求失败');
      });
    },
    queryUserOrgsByUserIdAndOrg(userId,orgId,item){
      this.orgModal = true;
      this.$http.get(Api.queryUserOrgsByUserId + "/" + userId + "/" + orgId).then(function(res){
        if(res.data.result == true){
          item.loading = false;
          item.expand = true;
          res.data.data.forEach(item=>{
            item.loading = false;
            item.expand = false;
            if(item.checked == 'false'){
              item.checked=false;
            }
            else{
              item.checked=true;
            }
            item.children = [];
          })
          if(res.data.data.length>0){
            delete item.checked;
            item.selected = true;
          }
          item.children = res.data.data;
        }
      }, function(res){
        this.$Message.error('请求失败');
      });
    },
    saveUserOrgs(){
      let checkNode = '';
      this.$refs.userOrgInfoTree.getCheckedAndIndeterminateNodes().forEach(item=>{
        if(item.isChild == true || item.children.length == 0 ||item.expand == false){
          checkNode += (item.orgId + "_1,");
        }else{
          checkNode += (item.orgId + "_0,");
        }
      })
      let param = {'orgId':checkNode};
      this.$http.post(Api.addUserOrg + "/" + this.selectedUserId,
          param,{emulateJSON:true}).then(function(res){
        this.orgModal = false;
      })
    },
    cancelUserOrgs(){
      this.orgModal = false;
    },
    treeSelect(nodes,node){

    },
    handleCreated(ztreeObj) {
      this.ztreeObj = ztreeObj;
    },
    save(row){
      this.$emit('getSelectModelData',row);
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;
      } else {
        this.tableHeight = this.tableHeight - 44;
      }
    },
    queryPosition(){
      let data = {
        fromPage : 1,
        pageSize : 1000,
        orgId : this.formCustom.orgId
      }
      this.$http.get(Api.queryPosition, {
        params: data
      }).then(res => {
        this.positions = res.data.data;
      })
    },
    orgNamesetOrgInfo(data) {
      this.formCustom.orgId = data[data.length - 1];
    },
    setOrgInfo(data) {
      this.formItem.orgId = data[data.length - 1];
    },
    sizeChange(size) {
      this.pagedata.pageSize = size
      this.query()
    },
    pageChange(pagenum) {
      this.pagedata.fromPage = pagenum
      this.query()
    },
    query() {
      this.reportSelectAll = [];
      this.buttonLoading = true
      let data = {
        startPage:this.pagedata.fromPage,
        size:this.pagedata.pageSize,
        conditions:this.formItem,
      };

      data.conditions.orgId = this.formItem.orgId;
      if (this.model) {
        data.conditions.companyId=this.companyId
      }else{
        data.conditions.companyId = sessionStorage('userId').getObject('userId').companyId;
      }
      // let url="http://localhost:30032/envinfo/SaStaffEnvinfo/all"
      let url=Api.getBaseUser
      this.$http.post(url, data
      ).then(res => {

        this.pagedata.total = res.data.data.totalSize;
        this.data1 = res.data.data.data;
        this.buttonLoading = false
      }).catch(e => {
        this.$Message.error('请求失败');
      })
    },
    reset() {
      this.formItem = {
        userName: "",
        loginId: "",
        orgId: "",
      };
      this.$refs.childOrg.resetCurrentOrg();
      this.query();
    },
    modaltage() {
      this.formCustom = {};
      this.$set(this.formCustom,'userName','');
      this.$set(this.formCustom,'loginId','');
      this.$set(this.formCustom,'mainCompanyName','');
      this.$set(this.formCustom,'mainOrgName','');
      this.$set(this.formCustom,'password',"");
      this.$set(this.formCustom,'password1',"");
      this.$set(this.formCustom,'mobileNumber','');
      this.$set(this.formCustom,'contactNumber','');
      this.modal2 = true;
    },
    modify(params) {
      this.positions = [];
      this.positions.push({positionId:params.row.positionId,positionName:params.row.positionName})
      this.tage = true;
      this.modal3 = true;
      this.orgId = params.row.orgId;
      this.orgName = params.row.orgName,
          this.formCustom = {
            userId: params.row.userId,
            userName: params.row.userName,
            orgId: params.row.orgId,
            orgName: params.row.orgName,
            positionId: params.row.positionId,
            positionName: params.row.positionName,
            loginId: params.row.loginId,
            email: params.row.email,
            //sex: params.row.sex,
            contactNumber: params.row.contactNumber,
            mobileNumber: params.row.mobileNumber
            //createDate: params.row.createDate
          }
    },
    remove(params) {
      this.$http.get(Api.deleteUser + '/' + params.row.userId).then(res => {
        this.$Message.success('删除成功!');
        this.query();
      }).catch(e => {
        this.$Message.error('请求失败');
      })
      this.$http.get(Api.deleteTaskByUserId + '/' + params.row.userId).then(res => {}).catch(e => {})
    },
    modalok() {
      this.$refs["formCustom"].validate((valid) => {
        if (valid) {
          if (this.tage) {
            this.formCustom.updateUserId = sessionStorage('userId').getObject('userId').userId;
            this.formCustom.updateDate = this.
                this.formCustom.orgInfo = {"orgId": this.formCustom.orgId};
            this.formCustom.position = {"positionId":this.formCustom.positionId};
            delete this.formCustom['orgId'];
            this.$http.post(Api.updateUser, this.formCustom).then(res => {
              this.tage = false
              this.modal2 = false
              this.modal3 = false
              this.$Message.success('成功!');
              this.query();
            }).catch(e => {
              this.$Message.error('请求失败');
            })
          } else {
            this.formCustom.orgInfo = {"orgId": this.formCustom.orgId};
            this.formCustom.position = {"positionId": this.formCustom.positionId};
            delete this.formCustom['orgId'];
            delete this.formCustom['positionId'];
            this.$http.post(Api.addUser, this.formCustom).then(res => {
              this.modal2 = false
              this.modal3 = false
              this.$Message.success('成功!');
              this.query();
            }).catch(e => {
              this.$Message.error('请求失败');
            })
          }
        } else {
          this.$Message.error('不能为空!');
        }
      })
    },
    modalcancel() {
      this.tage = false
      this.modal2 = false
      this.modal3 = false
    },
  },

}
</script>

<style lang='css' scoped>
@import '../../../index.css';

</style>
